import scala.actors._

/**
 * Takes passengers and bags that have been passed and sends them back to the
 * Driver so that they may exit the system gracefully - this is what represents
 * getting on the plane.
 * @author Samuel Nelson, Robert Vrooman, James Fitzgerald, Gabriel Marcano
 */
class Security(lineNum: Int, jail: Jail) extends Actor {
  private val _lineNumber = lineNum;
  private var seenReports = Map[Long, Boolean]();
  private var currentStart = 0
  private var currentShutdown = 0

  def lineNumber = _lineNumber;
  
  def act() {
    loop {
      react {
        //Check report message against current saved reports
        //If a saved report has the same ID as current report, pass or fail passenger
        //else add report to current report
        case report: Report =>
          println("Security " + lineNum + " has received one of Passenger " +
                  report.ID + "'s Reports.")
          if (seenReports.contains(report.ID)) {
            if (!seenReports.get(report.ID).get || !report.passedSecurity) {
              println("Security " + lineNum + " is sending Passenger " +
                      report.ID + " to Jail.")
              jail ! new Passenger(report.ID)
            } else {
              println("Passenger " + report.ID + " went to his/her airplane.");
            }
          } else {
            seenReports += (report.ID -> report.passedSecurity);
          }
        case Startup =>
          println("Security " + lineNum + " has received Startup.")
          currentStart += 1
          if(currentStart >= 2){
            println("Security " + lineNum + " is sending Startup to Jail.")
            jail ! Startup
          }

        case Shutdown =>
          println("Security " + lineNum + " has received Shutdown.")
          currentShutdown += 1
          shutdownRequested
      }
    }
  }

  // reactWithin(0) gives a TIMEOUT as soon as the mailbox is empty
  def shutdownRequested: Nothing = reactWithin(100) {
    case Shutdown => {
        println("Security " + lineNum + " has received another Shutdown.")
        currentShutdown += 1
        shutdownRequested
      }
    case TIMEOUT => {
        if(currentShutdown >= 2){
          println("Security " + lineNum + " is sending Shutdown to Jail.")
    	  jail ! Shutdown
          println("Security " + lineNum + " has now shutdown.")
    	  exit
        }
      }
  }

}